package com.topscore.uke.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.topscore.uke.R;
import com.topscore.uke.entities.TeamMemberItem;
import com.topscore.uke.entities.UserInfo;
import com.topscore.uke.mvp.contractors.GetTeamStaffListContractor;
import com.topscore.uke.mvp.presenters.GetTeamStaffListPresenter;
import com.topscore.uke.ui.ToolBarCompatActivity;
import com.topscore.uke.ui.fragments.StaffSearchResultFragment;
import com.topscore.uke.ui.loadsir_callback.ErrorCallBack;
import com.topscore.uke.ui.loadsir_callback.LoadingCallBack;
import com.topscore.uke.utils.UserInfoManager;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MyTeamStaffListActivity extends ToolBarCompatActivity implements GetTeamStaffListContractor.View {

    @Bind(R.id.search_edt)
    EditText searchEdt;
    @Bind(R.id.root_recycler)
    RecyclerView rootRecycler;
    @Bind(R.id.clear_btn)
    ImageView clearBtn;

    private GetTeamStaffListContractor.Presenter mPresenter;
    private RecyclerAdapter mAdapter;

    private LoadService mLoadService;

    private FragmentManager mFragmentManager;

    private StaffSearchResultFragment mSearchResultFragment;

    private OnSearchStaffListener mSearchStaffListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_team_staff_list);
        ButterKnife.bind(this);
        setCentralTitle("成员");
        initViews();
    }

    private void initViews() {
        mLoadService = LoadSir.getDefault().register(rootRecycler, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                mPresenter.getStaffList();
            }
        });
        mAdapter = new RecyclerAdapter();
        rootRecycler.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rootRecycler.addItemDecoration(new StickyRecyclerHeadersDecoration(mAdapter));
        rootRecycler.setAdapter(mAdapter);
        searchEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    clearBtn.setVisibility(View.VISIBLE);
                } else {
                    clearBtn.setVisibility(View.GONE);
                    FragmentTransaction transaction = mFragmentManager.beginTransaction();
                    transaction.hide(mSearchResultFragment).commit();
                }
            }
        });
        searchEdt.setOnEditorActionListener((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                String name = searchEdt.getText().toString();
                FragmentTransaction transaction = mFragmentManager.beginTransaction();
                transaction.show(mSearchResultFragment).commit();
                mSearchStaffListener.onSearch(name);
                return true;
            }
            return false;
        });

        clearBtn.setOnClickListener(view -> {
            searchEdt.setText("");
        });

        mFragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        mSearchResultFragment = new StaffSearchResultFragment();
        mSearchStaffListener = mSearchResultFragment;
        transaction.add(R.id.fragment_container, mSearchResultFragment).hide(mSearchResultFragment).commit();
        mPresenter = new GetTeamStaffListPresenter(this);
        mPresenter.getStaffList();
    }

    @Override
    public void onGetDataSuccess(List<TeamMemberItem> data) {
        mAdapter.setNewData(data);
    }

    private class RecyclerAdapter extends BaseQuickAdapter<TeamMemberItem, BaseViewHolder> implements StickyRecyclerHeadersAdapter {

        public RecyclerAdapter() {
            super(R.layout.team_staff_item, new ArrayList<>());
        }


        @Override
        protected void convert(BaseViewHolder holder, TeamMemberItem item) {
            holder.setText(R.id.name_tv, item.getMemberName());
            holder.itemView.setOnClickListener(view -> {
                Intent intent = new Intent(mContext, StaffInformationActivity.class);
                intent.putExtra("userId", String.valueOf(item.getMemberId()));
                intent.putExtra("role", UserInfoManager.getUserInfo().getRole());
                startActivity(intent);
            });
        }

        @Override
        public long getHeaderId(int i) {
            return Integer.valueOf(getData().get(i).getIsHead()) == 1 ? 0 : 1;
        }

        @Override
        public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
            View view = getLayoutInflater().inflate(R.layout.team_staff_sticky_header, viewGroup, false);
            return new RecyclerView.ViewHolder(view) {
            };
        }

        @Override
        public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
            TextView textView = (TextView) viewHolder.itemView.findViewById(R.id.type_tv);
            textView.setText(Integer.valueOf(getData().get(i).getIsHead()) == 1 ? "团队管理" : "团队成员");
        }
    }

    @Override
    public void onLoading(String loadingMessage) {
        mLoadService.showCallback(LoadingCallBack.class);
    }

    @Override
    public void onLoadFinished() {
        mLoadService.showSuccess();
    }

    @Override
    public void onFail(int code, String errorMessage) {
        mLoadService.showCallback(ErrorCallBack.class);
        Toast.makeText(mContext, errorMessage, Toast.LENGTH_SHORT).show();
    }

    public interface OnSearchStaffListener {
        void onSearch(String memberName);
    }
}
